<?php
/*
This class dispatches the request, will write more on this.
*/

class Dispatcher
{
	var $controller;
	
	function __construct()
	{

	
	}
		
	
	public function dispatch()
	{
		foreach($_REQUEST as $key => $value) {
			if(!is_array($value)){
				${$key} = trim(rawurldecode($value));
				//echo "$key $value<br>";
			}
			else{
				${$key} = $value;
			}	
		}
		
		$page = (isset($page)) ? $page : 'home';
		//Including all necessary files
		include ('includes.php');
		
		//Initializing controller object
		$controllerClass = $page."Controller";
		$this -> controller = new $controllerClass;
		
		//Setting applicatoin path to controller appPath var
		$this -> controller -> appPath = APPROOT;
		
		//Initializing model object
		$modelClass = $page.'Model';
		//This is attaching the model object with controller to access it in controller
		$this -> controller -> $page = new $modelClass;
			
		//setting view::page variable 
		$this -> controller -> page = $page;
		
		//Passing query string to controller data object
		$this -> controller -> data = $_REQUEST;
		
		//This is to get file data
		$this -> controller -> file = $_FILES;
		
		//Setting APIs array to controller to load it
		$this -> controller -> api = $arrAPIs;
		
		//Setting protected pages array to controller proctedPages var
		$this -> controller -> protectedPages = $arrProtectedPages;
		
		//protecting page if needed
		$this -> controller -> protect($page);
		

		//Setting protected pages array to controller proctedPages var
		$this -> controller -> accountTypes = $accountTypes;

		//Setting theme for view::setTheme
		$tempTheme = "finna";					 //$this -> getTheme($page, $pageViews);
		$this -> controller -> setTheme($tempTheme);
		
		//Check
		$sub = (isset($sub)) ? $sub : 'index';
		$this -> controller -> method = $sub;
		
		return $this -> controller;
	}
	
	public function renderView($theme = 'admin')
	{
		foreach($_REQUEST as $key => $value) {
			if(!is_array($value)){
				${$key} = trim(rawurldecode($value));
				//echo "$key $value<br>";
			}
			else{
				${$key} = $value;
			}	
		}
		
		//Including all necessary files
		include ('constants.php');
		include ('controllers/controller.php');
		
		$this -> controller = new appController();
		
		$this -> controller -> page = isset($page) ? $page : 'home';
		
		//Setting APIs array to controller to load it
		$this -> controller -> api = $arrAPIs;
		
		//Setting theme for view::setTheme
		$tempTheme = $this -> getTheme($page, $admin_pages);
		$this -> controller -> setTheme($tempTheme);
		
		$this -> controller -> render();
		
	}
	
	//this function getting the theme 
	private function getTheme($page, $pageViews)
	{
		foreach($pageViews as $view => $val)
		{
			if(in_array($page, $val['pages']))
			{
				return $val['theme'];
			}
		}
			
	}
	

	
}
		
?>